/*
 * @Author: shiyue 2647472992@qq.com
 * @Date: 2024-02-17 10:07:37
 * @LastEditors: shiyue 2647472992@qq.com
 * @LastEditTime: 2024-02-17 11:55:04
 * @FilePath: /vscodecpp/test-2-16/Tcpclient.cpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <iostream>
#include <ctime>
#include "Socket.hpp"
#include "Protocol.hpp"
void Userage(const std::string &manual)
{
    std::cout << "\nUserage " << manual << "ip "
              << " port"
              << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Userage(argv[0]);
        exit(0);
    }
    uint16_t port = std::stoi(argv[2]);
    std::string ip = argv[1];
    Socket sock;
    sock.Build_Socket();
    bool check = sock.Connect(ip, port);
    if (!check)
        return 1;
    int sockfd = sock.Fd();
    srand(time(nullptr));
    std::string ops = "+-*/%";
    std::string inbuff_stream;
    int cnt = 1;
    while (true)
    {
        std::cout << "----------------------------" << std::endl;
        std::cout << "第" << cnt << "次测试--" << std::endl;
        int x = rand() % 10 + 1;
        int y = rand() % 5 + 1;
        char op = ops[rand() % ops.size()];
        Request rt(x, y, op);
        rt.Print();
        std::string package;
        rt.Serialize(&package);
        package = Encode(package);
        write(sockfd, package.c_str(), package.size());
        char buff[1024];
        sleep(2);
        size_t n = read(sockfd, buff, sizeof(buff));
        if (n > 0)
        {
            buff[n] = 0;
            inbuff_stream += buff;
            //std::cout << inbuff_stream << std::endl;
            std::string content;
            bool check = Decode(inbuff_stream, &content);
            Respond rd;
            rd.Deserialize(content);
            rd.Print();
            std::cout
                << "-------------------" << std::endl;
                sleep(2);
        }
        ++cnt;
    }

    return 0;
}